package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String, Map<String, HttpServlet>> appServletMap;

    public RequestProcessor(Socket socket, Map<String, Map<String, HttpServlet>> appServletMap) {
        this.socket = socket;
        this.appServletMap = appServletMap;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            String url = request.getUrl().substring(1);
            String contextPath = url;
            if(contextPath.contains("/")){
                contextPath  = url.substring(0,url.indexOf("/"));
            }
            String actualUrl = "/";
            if(url.contains("/")){
                actualUrl = url.substring(url.indexOf("/"));
            }

            if(appServletMap.get(contextPath)==null || appServletMap.get(contextPath).get(actualUrl) == null) {
                response.outputHtml(actualUrl);
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = appServletMap.get(contextPath).get(actualUrl);
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
